package com.xydpeng.rpc.serialize.handler;

import com.xydpeng.rpc.common.model.FastRpcRequest;
import com.xydpeng.rpc.common.model.FastRpcResponse;
import com.xydpeng.rpc.protocol.FastRpcProtocol;
import com.xydpeng.rpc.protocol.MsgType;
import com.xydpeng.rpc.serialize.Serialization;
import com.xydpeng.rpc.serialize.SerializationFactory;
import com.xydpeng.rpc.serialize.SerializationType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2023/4/13
 * @description:
 */
public class DeserializeHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FastRpcProtocol) {
            FastRpcProtocol protocol = (FastRpcProtocol) msg;
            Object body = protocol.getBody();
            if (body instanceof byte[]) {
                Serialization serialization = SerializationFactory.getInstance(SerializationType.findByType(protocol.getHeader().getSerialization()));

                body = serialization.deserialize((byte[]) body, resolveClass(MsgType.findByType(protocol.getHeader().getMsgType())));
                protocol.setBody(body);
            }
        }
        super.channelRead(ctx, msg);
    }


    private Class resolveClass(MsgType type) {
        switch (type) {
            case REQUEST:
                return FastRpcRequest.class;
            case RESPONSE:
                return FastRpcResponse.class;
            case HEARTBEAT:
                return null;
        }
        throw new IllegalArgumentException("msgType is illegal:" + type);
    }
}
